import React from "react";
import axios from "axios";
import "../css/StoreList.css";
import { connect } from "react-redux";
import { addCart } from "../redux/actions";

class StoreList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      storeList: []
    }
  }

  render() {
    return (
      <div>
        <div>
          <button onClick={() => {
            this.props.history.push("/cart")
          }}>购物车</button>
        </div>
        <div>
          <div className="store_list_container">
            {
              this.state.storeList.map((element) => {
                return <div className="store_item_container">
                  <div className="store_item_img_container">
                    <img src={element.productImage} />
                  </div>
                  <div className="store_item_info">
                    <p>{element.productName}</p>
                  </div>
                  <div className="store_item_info">
                    <p>{element.salePrice}</p>
                  </div>
                  <div>
                    <button onClick={() => {
                      this.props.addItemToCart(addCart(element))
                    }}>加入购物车</button>
                  </div>
                </div>
              })
            }
          </div>
        </div>
      </div>
    );
  }

  componentDidMount() {
    //发送异步请求
    axios.get("http://localhost:3000/data.json").then((res) => {
      console.log(res);
      this.setState({
        storeList: res.data.result.list
      })
    })
  }
}

function mapStateToProps(rootReducer) {
  return {

  }
}

function mapActionToProps(dispatch) {
  return {
    addItemToCart: (action) => { dispatch(action) }
  }
}

export default connect(mapStateToProps, mapActionToProps)(StoreList);